// 水质数据状态管理
import { defineStore } from 'pinia'

export const useWaterQualityStore = defineStore('waterQuality', {
  state: () => ({
    // 实时水质数据
    realtimeData: {
      phValue: 0,
      temperature: 0,
      turbidity: 0,
      totalNitrogen: 0,
      totalPhosphorus: 0,
      conductivity: 0,
      dataQuality: 1,
      collectTime: null
    },
    
    // 历史数据
    historyData: [],
    
    // 统计数据
    statisticsData: {
      daily: [],
      weekly: [],
      monthly: []
    },
    
    // 异常数据
    anomalyData: [],
    
    // 加载状态
    loading: false,
    
    // 错误信息
    error: null
  }),

  getters: {
    // 获取当前水质等级
    getWaterQualityLevel: (state) => {
      const { phValue, temperature, turbidity } = state.realtimeData
      
      // 简单的水质等级判断逻辑
      let score = 0
      
      // pH值评分 (6.5-8.5为最佳)
      if (phValue >= 6.5 && phValue <= 8.5) {
        score += 25
      } else if (phValue >= 6.0 && phValue <= 9.0) {
        score += 15
      } else {
        score += 5
      }
      
      // 温度评分 (20-25°C为最佳)
      if (temperature >= 20 && temperature <= 25) {
        score += 25
      } else if (temperature >= 15 && temperature <= 30) {
        score += 15
      } else {
        score += 5
      }
      
      // 浊度评分 (越低越好)
      if (turbidity < 1000) {
        score += 25
      } else if (turbidity < 2000) {
        score += 15
      } else if (turbidity < 3000) {
        score += 10
      } else {
        score += 5
      }
      
      // 三项指标评分合计
      
      if (score >= 80) return { level: '优秀', color: '#4cd964' }
      if (score >= 60) return { level: '良好', color: '#91cc75' }
      if (score >= 40) return { level: '一般', color: '#f0ad4e' }
      return { level: '较差', color: '#dd524d' }
    },
    
    // 获取异常数据数量
    getAnomalyCount: (state) => {
      return state.anomalyData.filter(item => item.handleStatus === 1).length
    },
    
    // 获取数据质量状态
    getDataQualityStatus: (state) => {
      return state.realtimeData.dataQuality === 1 ? '正常' : '异常'
    }
  },

  actions: {
    // 更新实时数据
    updateRealtimeData(data) {
      this.realtimeData = { ...this.realtimeData, ...data }
    },
    
    // 设置历史数据
    setHistoryData(data) {
      this.historyData = data
    },
    
    // 设置统计数据
    setStatisticsData(data) {
      this.statisticsData = { ...this.statisticsData, ...data }
    },
    
    // 设置异常数据
    setAnomalyData(data) {
      this.anomalyData = data
    },
    
    // 添加异常数据
    addAnomalyData(anomaly) {
      this.anomalyData.unshift(anomaly)
    },
    
    // 更新异常处理状态
    updateAnomalyStatus(anomalyId, status) {
      const anomaly = this.anomalyData.find(item => item.anomalyId === anomalyId)
      if (anomaly) {
        anomaly.handleStatus = status
      }
    },
    
    // 设置加载状态
    setLoading(loading) {
      this.loading = loading
    },
    
    // 设置错误信息
    setError(error) {
      this.error = error
    },
    
    // 清除错误信息
    clearError() {
      this.error = null
    }
  }
})
